package coroutines.dispatcher

import kotlinx.coroutines.*
import java.util.concurrent.Executors
import kotlin.coroutines.CoroutineContext

class CoroutineDispatcherTest {
}

fun main() {
    runBlocking {
        // 运行在父协程的上下文中，即 runBlocking 主协程
        launch {
            println("main runBlocking      : I'm working in thread ${Thread.currentThread().name}")
            println()
        }
        // 运行在父协程的上下文中，即 runBlocking 主协程
//        launch(Dispatchers.Main) { println("main runBlocking      : I'm working in thread ${Thread.currentThread().name}") }
        // 不受限的——将工作在主线程中
        launch(Dispatchers.Unconfined) {
            println("Unconfined            : I'm working in thread ${Thread.currentThread().name}")
            println()
        }
        // 将会获取默认调度器
        launch(Dispatchers.IO) {
            println("IO               : I'm working in thread ${Thread.currentThread().name}")
            println()
        }
        // 将会获取默认调度器
        launch(Dispatchers.Default) {
            println("Default               : I'm working in thread ${Thread.currentThread().name}")
            println()
        }
        // 将使它获得一个新的线程
        launch(newSingleThreadContext("MyOwnThread")) {
            println("newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}")
            println()
        }

        launch(object : CoroutineDispatcher() {
            override fun dispatch(context: CoroutineContext, block: Runnable) {
                Thread {
                    block.run()
                }.start()
            }
        }) {
            println("customDispatcher               : I'm working in thread ${Thread.currentThread().name}")
            println()
        }

        launch {
            async(Executors.newSingleThreadExecutor().asCoroutineDispatcher()) {
                println("asCoroutineDispatcher() async : I'm working in thread ${Thread.currentThread().name}")
                println()
            }
        }

        launch {
            withContext(Executors.newSingleThreadExecutor().asCoroutineDispatcher()) {
                println("asCoroutineDispatcher() async : I'm working in thread ${Thread.currentThread().name}")
                println()
            }
        }
    }
}